//
//  VistorView.swift
//  WeiBoDemo
//
//  Created by China Dragon on 2023/8/25.
//

import UIKit

/// 访客视图的协议（代理）
//protocol VistorViewDelegate:NSObjectProtocol{
//    /// 注册
//    func vistorViewDidRegister()
//    /// 登录
//    func vistorViewDidLogin()
//
//}

/// 访客视图 - 处理用户未登录的显示界面
class VistorView: UIView {
    
    //定义代理,weak 避免循环引用, weak 变量必须是可选项 ?
//    weak var delegate: VistorViewDelegate?
    
    // MARK: - 监听方法
//    @objc private func clickLogin(){
//        delegate?.vistorViewDidLogin()
//    }
//
//    @objc private func clickRegister(){
//        delegate?.vistorViewDidRegister()
//    }
    

    // MARK: - 设置视图信息
    /// - parameter imageName: 图片名称，首页设置为nil
    /// - parameter title: 消息文字
     func setupInfo(imageName: String?, desc: String){
        messageLabel.text = desc
        
        //如果图片名称为nil，说明是首页，直接返回
        guard let imgName = imageName else {
            startAnim()
            return
        }
        
        iconView.image = UIImage(named: imgName)
         
         //隐藏小房子
         homeIconView.isHidden = true
         /*
          iOS视图切换bringSubviewToFront：和sendSubviewToBack：
          https://blog.csdn.net/qq_27597629/article/details/105565729
          
          将一个UIView显示在最前面只需要调用其父视图的 bringSubviewToFront（）方法。

          将一个UIView层推送到背后只需要调用其父视图的 sendSubviewToBack（）方法。
          */
         //将遮罩图片移到底层
         sendSubviewToBack(maskIconView)
    }
    
    // MARK: - 启动首页转轮动画
    private func startAnim(){
        let anim = CABasicAnimation(keyPath: "transform.rotation")
//        anim.toValue = 2 * M_PI // 一圈
        anim.toValue = 2 * Double.pi // 一圈
        anim.repeatCount = MAXFLOAT
        anim.duration = 20 // 20秒
        
        // 完成后不删除，用在不断重复的动画上，当动画绑定的图层对应的视图被销毁时，动画会自动被销毁
        anim.isRemovedOnCompletion = false
        
        // 添加到图层
        iconView.layer.add(anim, forKey: nil)
        
    }
    
    
    // MARK: - 构造函数
    // initwithFrame 是 UIView 指定的构造函数， 使用 SB(Storybodard) 和 xib 不会调用下面这个函数
    override init(frame: CGRect) {//使用纯代码 开发的入口
        super.init(frame: frame)
        setUpUI()
    }

    // initwithCoder - 使用 SB(Storybodard) 和 xib 开发加载的函数，使用纯代码不会调用下面这个函数
    required init?(coder: NSCoder) {
        
        //如果使用SB开发，调用这个函数，会导致程序直接崩溃
        //阻止SB使用当前自定义视图
//        fatalError("init(coder:) has not been implemented")
        
        super.init(coder: coder)
        setUpUI()
    }
    
    // MARK: - 懒加载控件
    // 图标 使用 image: 构造函数创建的 UIImageView， 默认就是 image 的大小
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
//    private lazy var iconView: UIImageView = UIImageView(imageName: "visitordiscover_feed_image_smallicon")
    //遮罩
//    private lazy var maskIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
    private lazy var maskIconView: UIImageView = UIImageView(imageName: "visitordiscover_feed_mask_smallicon")
    
    private lazy var homeIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
//    private lazy var homeIconView: UIImageView = UIImageView(imageName: "visitordiscover_feed_image_house")
    
    private lazy var messageLabel: UILabel = UILabel(title: "关注一些人，会这里看看有什么惊喜")
//    private lazy var messageLabel: UILabel = {
//        let label = UILabel()
//        label.text = "关注一些人，会这里看看有什么惊喜, 关注一些人，会这里看看有什么惊喜, 关注一些人，会这里看看有什么惊喜"
//        label.textColor = UIColor.darkGray
//        label.font = UIFont.systemFont(ofSize: 14)
//        label.numberOfLines = 0// 允许换行, 还需要指定宽高
//        label.textAlignment = NSTextAlignment.center //文字居中
//        return label
//    }()
    
//    private lazy var registerButton: UIButton = {
//        let button = UIButton()
//        button.setTitle("注册", for: UIControl.State.normal)
//        button.setTitleColor(UIColor.orange, for: UIControl.State.normal)
//
//        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControl.State.normal)
//
//        return button
//    }()
    
//    private lazy var registerButton: UIButton = UIButton(title: "注册", color: UIColor.orange, imageName: "common_button_white_disable")
//    private lazy var loginButton: UIButton = UIButton(title: "登录", color: UIColor.darkGray, imageName: "common_button_white_disable")
    
    // 配合 通过监听方法传递点击事件，将 private 去掉
     lazy var registerButton: UIButton = UIButton(title: "注册", color: UIColor.orange, imageName: "common_button_white_disable")
     lazy var loginButton: UIButton = UIButton(title: "登录", color: UIColor.darkGray, imageName: "common_button_white_disable")
    
//    private lazy var loginButton: UIButton = {
//        let button = UIButton()
//        button.setTitle("登录", for: UIControl.State.normal)
//        button.setTitleColor(UIColor.orange, for: UIControl.State.normal)
//
//        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControl.State.normal)
//
//        return button
//    }()
}

extension VistorView{
    /// 设置界面
    private func setUpUI(){
        
        //1、添加控件
        addSubview(iconView)
        addSubview(maskIconView)
        addSubview(homeIconView)
        addSubview(messageLabel)
        addSubview(registerButton)
        addSubview(loginButton)
        
        /*
         
         自动布局 查看源码
         NSLayoutConstraint
         
         /* Create constraints explicitly.  Constraints are of the form "view1.attr1 = view2.attr2 * multiplier + constant"
          If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute.
          Use of this method is not recommended. Constraints should be created using anchor objects on views and layout guides.
          */
         
         */
        
        
        //2、设置自动布局
        /*
         
         - 添加约束需要添加到父视图上
         
         - 子视图最好有一个统一的参照物
         
         NSLayoutConstraint.Attribute.centerX 水平居中
         */
        
        //translatesAutoresizingMaskIntoConstraints 默认是 true，支持使用 setFrame 的方式来设置空间位置
        // false 支持使用自动布局来设置空间位置
//        iconView.translatesAutoresizingMaskIntoConstraints = false
//        homeIconView.translatesAutoresizingMaskIntoConstraints = false
        for v in subviews{
            v.translatesAutoresizingMaskIntoConstraints = false
        }
        
        
        
        // 1、图标
        addConstraint(itemView: iconView,toItemView: nil, yConst: -100)//向上偏移60像素
//        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0))
//
//        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0))
//
       
        // 2、小房子
        addConstraint(itemView: homeIconView, toItemView: iconView)
//        addConstraint(NSLayoutConstraint(item: homeIconView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0))
//
//        addConstraint(NSLayoutConstraint(item: homeIconView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0))
        
        //3、消息
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: iconView, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0))

        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: iconView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: 16))
        
        //设置 messageLabel 宽高
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1.0, constant: 300))

        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute ,multiplier: 1.0, constant: 80))
        
        
        //4、添加注册按钮
        addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutConstraint.Attribute.left, relatedBy: NSLayoutConstraint.Relation.equal, toItem: messageLabel, attribute: NSLayoutConstraint.Attribute.left, multiplier: 1.0, constant: 0))

        addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: messageLabel, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: 16))
        
        //设置 registerButton 宽高
        addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1.0, constant: 100))

        addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute ,multiplier: 1.0, constant: 36))
        
        
        //4、添加注册按钮
        addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutConstraint.Attribute.right, relatedBy: NSLayoutConstraint.Relation.equal, toItem: messageLabel, attribute: NSLayoutConstraint.Attribute.right, multiplier: 1.0, constant: 0))

        addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: messageLabel, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: 16))
        
        //设置 registerButton 宽高
        addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1.0, constant: 100))

        addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute ,multiplier: 1.0, constant: 36))
        
        
        // 遮罩图像
        /*
         VFL: 可视化格式语言
         H: 水平方向
         V: 垂直方向
         |：边界
         []: 包装控件
         views: 是一个字段[名字：控件名] - VFL - 字符串中表示控件的字符串
         metrics：是一个字典[名称：NSNumber] - VFL - 字符串中表示某一个数值
         
         */
        
//        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[mask]-0-|",options: [], metrics: nil, views: ["mask" : maskIconView]))
        //查看 constraints 方法源码，里面的 options 参数默认值为 []
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[mask]-0-|",metrics: nil, views: ["mask" : maskIconView]))
        
//        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[mask]-(-36)-[regButton]", options: [], metrics: nil, views: ["mask" : maskIconView, "regButton": registerButton]))
        //上面的和下面的效果一样，使用下面的写法
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[mask]-(btnHeight)-[regButton]", options: [], metrics: ["btnHeight": -36], views: ["mask" : maskIconView, "regButton": registerButton]))
        
        // 设置背景颜色 - 灰度图 R = G = B 在 UI元素中，大多数使用 灰度图，或者纯色图（安全色）
        backgroundColor = UIColor(white: 237.0 / 255.0, alpha: 1.0)
        
        
        
        // 添加 监听方法
//        registerButton.addTarget(self, action: "clickRegister", for: UIControl.Event.touchUpInside)
//        loginButton.addTarget(self, action: "clickLogin", for: UIControl.Event.touchUpInside)
        
    }
    
    /// 设置自动布局 - 添加约束需要添加到父视图上 - 设置统一参照物
    private func addConstraint(itemView: UIView, toItemView: UIView?, xConst: CGFloat? = nil, yConst: CGFloat? = nil){
        addConstraint(NSLayoutConstraint(item: itemView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: toItemView ?? self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: xConst ?? 0))
        
        addConstraint(NSLayoutConstraint(item: itemView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: toItemView ?? self, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: yConst ?? 0))
    }
}
